package com.hefan.mgmt.controller.task;

import com.hefan.mgmt.configCenter.MgmtConfigCenter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>登录与注册</p>
 */
@RequestMapping("/")
@Controller
public class LoginRegController {
  private static Logger logger = Logger.getLogger(LoginRegController.class);

  @Resource
  private MgmtConfigCenter mgmtConfigCenter;
  /**
   * goLogin
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping("/goLogin")
  public String goLogin() {
    logger.info("跳转到登录页面");
    return "login";
  }

  /***
   * 用户登录
   * @param request
   * @return
   */
  @RequestMapping("goToLogin")
  @ResponseBody
  public String goToLogin(final HttpServletRequest request) {
    logger.info("进入登录请求");
    //用户名
    String userName = request.getParameter("userName");
    //密码
    String userPwd = request.getParameter("userPwd");

    //判断用户名 与密码是否为空
    if (StringUtils.isBlank(userName) || StringUtils.isBlank(userPwd)) {
      //登录失败
      return "1";
    }
    Map<String, String> userMap = mgmtConfigCenter.getPublicConfig();
    if (userMap == null) {
      //登录失败
      return "2";
    }
    String name=userMap.get("userName");
    String pwd=userMap.get("password");
    if (name.equals(userName) && pwd.equals(userPwd)) {
      request.getSession().setAttribute("user", userMap);
      return "0";
    }
    return "2";
  }

  /**
   * 用户退出系统
   *
   * @param session
   * @return
   */
  @RequestMapping(value = "/user/logout")
  public String logout(final HttpServletRequest request, final HttpServletResponse response) {
    request.getSession().invalidate();
    return "login";
  }
}
